package person.bing.fbcloud.controller;


import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import person.bing.fbcloud.api.dto.PostDTO;
import person.bing.fbcloud.api.entity.Post;
import person.bing.fbcloud.common.core.exception.CheckedException;
import person.bing.fbcloud.common.core.util.R;
import person.bing.fbcloud.repository.PostRepository;
import person.bing.fbcloud.service.PostService;

import java.util.List;

/**
 * <p>
 * 帖子
 * </p>
 *
 * @author mengfb
 * @since 2019-06-24
 */
@RestController
@RequestMapping("/post")
public class PostController {
    @Autowired
    private PostService postService;
    @Autowired
    private PostRepository postRepository;

    /**
     * 发帖
     * @param postDTO
     * @return
     */
    @PostMapping
    public R addPost(@RequestBody PostDTO postDTO){
        String title = postDTO.getTitle();
        String text = postDTO.getText();
        String userCode = postDTO.getUserCode();
        String categoryKey = postDTO.getCategoryKey();
        if (StrUtil.isEmpty(title)){
            throw new CheckedException("title不能为空");
        }
        if (StrUtil.isEmpty(text)){
            throw new CheckedException("text不能为空");
        }
        if (StrUtil.isEmpty(userCode)){
            throw new CheckedException("userCode不能为空");
        }
        postService.addPost(userCode,categoryKey,title,text);

        postRepository.save(postDTO);
        return new R();
    }

    /**
     * 根据categoryKey获取帖子列表
     * @param categoryKey
     * @return
     */
    @GetMapping("/{categoryKey}")
    public R getPostByCategoryKey(@PathVariable String categoryKey){
        return new R(postService.getPost(categoryKey));
    }

    /**
     * 根据帖子id获取详情
     * @param postId
     * @return
     */
    @GetMapping("/getPostDetails/{postId}")
    public R getPostDetails(@PathVariable String postId){
        return new R(postService.getPostDetails(postId));
    }

    /**
     * 测试
     * @return
     */
    @GetMapping("test")
    public R test(String title){
        List<Post> byTitle = postRepository.findByTitle(title);
        return new R(byTitle);
    }
}
